
package com.yimixian.app.ui;

import android.animation.ArgbEvaluator;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.UMengConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.fragment.OrderMvpFragment;
import com.yimixian.app.model.Order;
import com.yimixian.app.net.HttpApi;
import com.yimixian.app.order.OrderDetailActivity;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class SlideViewPager extends FrameLayout {

    @InjectView(R.id.tv_left)
    TextView mTvLeft;
    @InjectView(R.id.tv_right)
    TextView mTvRight;
    @InjectView(R.id.view_pager)
    ViewPager mViewPager;
    @InjectView(R.id.iv_divider)
    ImageView mIvDivider;
    @InjectView(R.id.title_bar_back_button)
    ImageView mTitleBarBackButton;
    View mLeftView;
    View mRightView;
    ISlideViewPager mISlideViewPager;
    int mSelectedTabIndex = 0;
    @InjectView(R.id.ll_bottom_bar)
    public LinearLayout mRlBottomBar;

    String mURLComplain = "";
    String mURLComment = "";
    String mCommentName = "";
    String mComplainName = "";
    @InjectView(R.id.comment_order)
    TextView mCommentOrder;
    @InjectView(R.id.complain_order)
    TextView mComplainOrder;
    @InjectView(R.id.iv_divider_line)
    ImageView mIvDividerLine;
    @InjectView(R.id.fl_mask)
    FrameLayout mFlMask;
    @InjectView(R.id.iv_divider2)
    ImageView mIvDivider2;
    @InjectView(R.id.cancel_order)
    TextView cancel_order;
    @InjectView(R.id.count_down_text)
    public TextView count_down_text;
    @InjectView(R.id.pay_button)
    public TextView pay_button;

    private View dialog;
    private Dialog dialogLoading;
    private DataManager mDataManager;
    private Order mOrder;

    public void setISlideViewPager(ISlideViewPager ISlideViewPager) {
        mISlideViewPager = ISlideViewPager;
    }

    public SlideViewPager(Context context) {
        super(context);
        initSlideViewPager();
    }

    public SlideViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        initSlideViewPager();
    }

    public SlideViewPager(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initSlideViewPager();
    }

    private void initSlideViewPager() {
        LayoutInflater.from(getContext()).inflate(R.layout.slide_viewpager, this);
        ButterKnife.inject(this);
        mDataManager = DataManager.getInstance();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    public void bind(ISlideViewPager iSlideViewPager) {
        setISlideViewPager(iSlideViewPager);
        mTvLeft.setText(iSlideViewPager.getLeftTitleName());
        mTvRight.setText(iSlideViewPager.getRightTitleName());
        mLeftView = iSlideViewPager.getLeftView();
        mRightView = iSlideViewPager.getRightView();
        initViewPager();
    }

    private void initViewPager() {
        PagerAdapter pagerAdapter = new PagerAdapter() {
            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }

            @Override
            public int getCount() {
                return 2;
            }

            @Override
            public void destroyItem(ViewGroup container, int position,
                    Object object) {
                container.removeView(getPageByPosition(position));

            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View page = getPageByPosition(position);
                container.addView(page);
                if (position == 0) {
                    mISlideViewPager.initLeftView();
                } else {
                    mISlideViewPager.initRightView();

                }
                return page;
            }

            private View getPageByPosition(int position) {
                return position == 0 ? mLeftView : mRightView;
            }

        };
        mViewPager.setAdapter(pagerAdapter);
        ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                onScrollTextAlpha(positionOffset, position);
                translateBottomLine(positionOffset);
            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    mSelectedTabIndex = 0;
                    mIvDivider.setVisibility(View.VISIBLE);
                    mIvDivider2.setVisibility(View.INVISIBLE);
                } else {
                    mSelectedTabIndex = 1;
                    mIvDivider.setVisibility(View.INVISIBLE);
                    mIvDivider2.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        };
        mViewPager.addOnPageChangeListener(onPageChangeListener);
        mViewPager.setCurrentItem(mSelectedTabIndex);
        onPageChangeListener.onPageSelected(mSelectedTabIndex);
        mTvLeft.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewPager.setCurrentItem(0);
            }
        });
        mTvRight.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewPager.setCurrentItem(1);
            }
        });
    }

    public void onScrollTextAlpha(float positionOffset, int position) {
        ArgbEvaluator evaluator = new ArgbEvaluator();
        int evaluate = (Integer) evaluator.evaluate(positionOffset, 0XFFff5a1e, 0XFF333333);
        int evaluate2 = (Integer) evaluator
                .evaluate(positionOffset, 0XFF333333, 0XFFff5a1e);
        if (position % 2 == 0) {
            mTvLeft.setTextColor(evaluate);
            mTvRight.setTextColor(evaluate2);
        } else {
            mTvLeft.setTextColor(evaluate2);
            mTvRight.setTextColor(evaluate);
        }
    }

    public void translateBottomLine(float positionOffset) {
        /*
         * float dx = (mTvRight.getX() - mTvLeft.getX()) * positionOffset; if
         * (dx != 0 && mIvDivider != null) {
         * mIvDivider.setScaleType(ImageView.ScaleType.MATRIX); Matrix m = new
         * Matrix(); m.postTranslate(dx, 0); mIvDivider.setImageMatrix(m); }
         */
    }

    public interface ISlideViewPager {
        View getLeftView();

        View getRightView();

        void initLeftView();

        void initRightView();

        String getLeftTitleName();

        String getRightTitleName();

        void onBackButtonClick();
    }

    public void showBackButton() {
        mTitleBarBackButton.setVisibility(View.VISIBLE);
        mTitleBarBackButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mISlideViewPager.onBackButtonClick();
            }
        });
    }

    public void showBottomBar() {
        mComplainOrder.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra(WebViewActivity.EXTRA_URL, mURLComplain);
                getContext().startActivity(intent);
            }
        });
        mCommentOrder.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra(WebViewActivity.EXTRA_URL, mURLComment);
                getContext().startActivity(intent);
            }
        });
        cancel_order.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                int type = 0;
                String text = "您确定要取消该订单么？";
                if (mOrder.deliveryInfo.index > 1) {
                    type = 1;
                    text = "您的订单已经分拣完毕，不可取消";
                } else if (!Strings.isNullOrEmpty(mOrder.cancelOrder.cancel_button_message)) {
                    type = 1;
                    text = mOrder.cancelOrder.cancel_button_message;
                }
                if (type == 0) {
                    dialog = UiUtils.showOKAndCancelDialog(getContext(), text, "确定", new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            UiUtils.hideDialog(dialog);
                            dialogLoading = UiUtils.showLoadingDialog(getContext(), "正在取消订单...");
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("token", (String) mDataManager.get(CacheKeys.TOKEN));
                            map.put("order_id", mOrder.id + "");
                            HttpApi.startPostRequest("/v5/orders/cancel_order", map, new HttpApi.RequestCallBack() {
                                @Override
                                public void requestSuccess(String result) {
                                    JSONObject json = null;
                                    String message = "订单取消成功";
                                    try {
                                        json = new JSONObject(result);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    if (json != null) {
                                        if (json.has("error")) {
                                            message = json.optJSONObject("error").optString("message");
                                            UiUtils.showToast(message);
                                            Map<String, String> hashMap = new HashMap<>();
                                            hashMap.put("EVENT", "fail");
                                            MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                                                    UMengConstants.NEW_ORDERDETAIL_CANCEL, hashMap);
                                            return;
                                        }
                                    }
                                    message = json.optString("message");
                                    UiUtils.showToast(message);
                                    Map<String, String> hashMap = new HashMap<>();
                                    hashMap.put("EVENT", "success");
                                    MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                                            UMengConstants.NEW_ORDERDETAIL_CANCEL, hashMap);
                                    OrderMvpFragment.CHANG_FLAG = ((Activity) getContext()).getIntent().
                                            getIntExtra(OrderDetailActivity.EXTRA_ORDER_POSITION, -1) + "," + json.optString("status");
                                    ((Activity) getContext()).finish();
                                }

                                @Override
                                public void requestError() {
                                    UiUtils.showToast("订单取消失败");
                                    Map<String, String> hashMap = new HashMap<>();
                                    hashMap.put("EVENT", "fail");
                                    MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                                            UMengConstants.NEW_ORDERDETAIL_CANCEL, hashMap);
                                }

                                @Override
                                public void alwaysDo() {
                                    if (dialogLoading != null)
                                        dialogLoading.dismiss();
                                }
                            });
                        }
                    }, "取消", new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            UiUtils.hideDialog(dialog);
                        }
                    });

                } else {
                    dialog = UiUtils.showOKDialog(getContext(), text, "确定", new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            UiUtils.hideDialog(dialog);
                        }
                    });
                }
            }
        });
    }

    public void setBottomBarStatus(String URLComplain, String URLComment, String complainName,
                                   String commentName) {
        setBottomBarStatus(URLComplain, URLComment, complainName, commentName, null);
    }

    public void setBottomBarStatus(String URLComplain, String URLComment, String complainName,
            String commentName, Order order) {
        mURLComplain = URLComplain;
        mURLComment = URLComment;
        mComplainName = complainName;
        mCommentName = commentName;
        mCommentOrder.setText(mCommentName);
        mComplainOrder.setText(mComplainName);
        mRlBottomBar.setVisibility(View.VISIBLE);
        mFlMask.setVisibility(View.VISIBLE);
        if (TextUtils.isEmpty(mURLComplain) && TextUtils.isEmpty(mURLComment)) {
//            mRlBottomBar.setVisibility(View.GONE);
//            mFlMask.setVisibility(View.GONE);
        }
        if(TextUtils.isEmpty(mURLComplain)) {
            mComplainOrder.setVisibility(View.GONE);
        }
        if(TextUtils.isEmpty(mURLComment)) {
            mCommentOrder.setVisibility(View.GONE);
        }
        mOrder = order;
        if(mOrder != null && mOrder.cancelOrder != null && mOrder.cancelOrder.cancel_button_visible){
            cancel_order.setVisibility(View.VISIBLE);
            cancel_order.setText(mOrder.cancelOrder.cancel_button_title);
        }else{
            cancel_order.setVisibility(View.GONE);
        }

        if(mComplainOrder.getVisibility() == View.GONE && mCommentOrder.getVisibility() == View.GONE && cancel_order.getVisibility() == View.GONE
            && count_down_text.getVisibility() == View.GONE && count_down_text.getVisibility() == View.GONE
            && pay_button.getVisibility() == View.GONE){
            mFlMask.setVisibility(View.GONE);
            mRlBottomBar.setVisibility(View.GONE);
        }

    }

    public void setCurrentPage(int page) {
        mViewPager.setCurrentItem(page);
     
    }

    public void showDivider() {
        mIvDividerLine.setVisibility(View.VISIBLE);
    }
}
